package com.qyhl.webtv.module_live.teletext.detail.popview.detail.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.ShoppingListBean;
import com.qyhl.webtv.commonlib.entity.live.ShoppingUserInfoBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.teletext.detail.popview.detail.TeleTextShopDetailContract;
import com.qyhl.webtv.module_live.teletext.detail.popview.detail.TeleTextShopDetailPresenter;
import com.weavey.loading.lib.LoadingLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_DETAIL)
public class TeleTextShopDetailActivity extends BaseActivity implements TeleTextShopDetailContract.TeleTextShopDetailView {
    @BindView(R2.id.cover)
    RoundedImageView cover;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.minus_btn)
    TextView minusBtn;
    @BindView(R2.id.num)
    TextView num;
    @BindView(R2.id.plus_btn)
    TextView plusBtn;
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.stock)
    TextView stock;
    @BindView(R2.id.deadline)
    TextView deadline;
    @BindView(R2.id.address)
    TextView address;
    @BindView(R2.id.tips)
    TextView tips;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.exchange_btn)
    TextView exchangeBtn;
    @BindView(R2.id.tips_tag)
    TextView tipTag;
    @BindView(R2.id.sale_out)
    RoundedImageView saleOut;
    @BindView(R2.id.description)
    TextView description;

    private String itemId;

    private ShoppingListBean mBean;

    private ShoppingUserInfoBean userInfoBean;

    private TeleTextShopDetailPresenter mPresenter;

    @Override
    protected int getContentView() {
        return R.layout.live_activity_shop_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        itemId = getIntent().getStringExtra("id");
        mPresenter = new TeleTextShopDetailPresenter(this);

        mPresenter.getDetail(itemId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(itemId);
            }
        });
    }


    @OnClick({R2.id.back_btn, R2.id.exchange_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back_btn) {
            finish();
        } else if (i == R.id.exchange_btn) {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        showLoading();
                        String username = CommonUtils.getInstance().getUserName();
                        mPresenter.getUserInfo(username);
                    } else {
                        showToast("尚未登录或登录已失效！");
                        RouterManager.routerLogin(TeleTextShopDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        }

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShoppingListBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mBean = bean;

        title.setText(bean.getItemName());
        score.setText(bean.getPrice());
        stock.setText("库存：" + bean.getStock() + "件");

        Glide.with(this)
                .load(bean.getItemPic())
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(cover);

        deadline.setText(StringUtils.isNotEmpty(bean.getExchangeDeadline()) ? DateUtils.translateToShopping(bean.getExchangeDeadline()) : "不限期");

        if (bean.getShop() != null) {
            address.setText(bean.getShop().getAddress());
        } else {
            address.setText("暂无商铺地址信息");
        }

        description.setText(bean.getItemDesc());

        if (StringUtils.isEmpty(bean.getOtherDesc())) {
            tips.setVisibility(View.GONE);
            tipTag.setVisibility(View.GONE);
        } else {
            tips.setVisibility(View.VISIBLE);
            tipTag.setVisibility(View.VISIBLE);
            tips.setText(bean.getOtherDesc());
        }

        if (bean.getStatus() == 0) {
            if (bean.getStock() == 0) {
                saleOut.setImageResource(R.drawable.shop_sale_out_icon);
                saleOut.setVisibility(View.VISIBLE);
                exchangeBtn.setEnabled(false);
                exchangeBtn.setText("已售罄");
            } else {
                exchangeBtn.setEnabled(true);
                saleOut.setVisibility(View.GONE);
            }
        } else if (bean.getStatus() == 3) {
            saleOut.setImageResource(R.drawable.shop_sale_overdue_icon);
            saleOut.setVisibility(View.VISIBLE);
            exchangeBtn.setEnabled(false);
            exchangeBtn.setText("已过期");
        } else {
            saleOut.setImageResource(R.drawable.shop_sale_off_icon);
            saleOut.setVisibility(View.VISIBLE);
            exchangeBtn.setEnabled(false);
            exchangeBtn.setText("已下架");
        }
    }

    @Override
    public void setError(String msg) {
        dismissLoading();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void setStock(int stock) {
        switch (mBean.getPriceType()) {
            case 1://普通积分
                if (userInfoBean.getAppScore() >= Integer.parseInt(mBean.getPrice())) {
                    if (stock <= 0) {
                        dismissLoading();
                        showToast("库存不足！");
                        mPresenter.getDetail(itemId);
                    } else {
                        mPresenter.doOrder(CommonUtils.getInstance().getNickName(), CommonUtils.getInstance().getUserName(), itemId, "1");
                    }
                } else {
                    dismissLoading();
                    showToast("积分不足！");
                }
                break;
            case 2://志愿者积分
                if (userInfoBean.getCivilizedScore() >= Integer.parseInt(mBean.getPrice())) {
                    if (stock <= 0) {
                        dismissLoading();
                        showToast("库存不足！");
                        mPresenter.getDetail(itemId);
                    } else {
                        mPresenter.doOrder(CommonUtils.getInstance().getNickName(), CommonUtils.getInstance().getUserName(), itemId, "1");
                    }
                } else {
                    dismissLoading();
                    showToast("积分不足！");
                }
                break;
            case 0:
                dismissLoading();
                showToast("暂无该类型积分！");
                break;
        }
    }

    @Override
    public void setUserInfo(ShoppingUserInfoBean bean) {
        userInfoBean = bean;
        if (mBean != null) {
            if (StringUtils.isEmpty(mBean.getExchangeDeadline())) {
                mPresenter.getStock(itemId);
            } else {
                if (DateUtils.isBeforeTime(mBean.getExchangeDeadline())) {
                    mPresenter.getStock(itemId);
                } else {
                    dismissLoading();
                    showToast("兑换时间已截止！");
                }
            }
        }
    }

    @Override
    public void orderSuccess(String msg) {
        dismissLoading();
        new OtherDialog.Builder(this)
                .setContentView(R.layout.live_dialog_shop_order_success)
                .setOnClickListener(R.id.check_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", msg);
                        bundle.putString("deadline", StringUtils.isNotEmpty(mBean.getExchangeDeadline()) ? mBean.getExchangeDeadline() : "不限期");
                        bundle.putString("start", mBean.getCreateTime());
                        RouterManager.router(ARouterPathConstant.SHOP_CODE, bundle);
                    }
                })
                .setDismissButton(R.id.cancel_btn)
                .show();
    }

    @Override
    public void orderError(String msg) {
        dismissLoading();
        new OtherDialog.Builder(this)
                .setContentView(R.layout.live_dialog_shop_order_error)
                .setText(R.id.error_msg, msg)
                .setDismissButton(R.id.cancel_btn)
                .show();
        if (msg.equals("库存不足！")) {
            mPresenter.getDetail(itemId);
        }
    }


}
